//
//  PaparazziAppDelegate.m
//  Paparazzi
//
//  Created by Miguel Sánchez Valdés on 27/04/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "PaparazziAppDelegate.h"
#import "PersonListViewController.h"
#import "RecentListViewController.h"

@implementation PaparazziAppDelegate

@synthesize window;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

	flickrFetcher = [FlickrFetcher sharedInstance];
	
	if ([flickrFetcher databaseExists]==NO)
	{
		[self fillDB];
		
		if (flickrContext != nil) 
		{
			if ([flickrContext hasChanges] == YES)
			{
				NSError *error = nil;
				BOOL isSaved = [flickrContext save:&error];
				NSLog(@"isSaved? %@", (isSaved ? @"YES" :@"NO") );
				
				if (isSaved == NO)
				{
					NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
					abort();				
				}
			}
		}
	}
	else 
	{
		flickrContext = [flickrFetcher managedObjectContext];
	}
    
	navControllerContacts = [[UINavigationController alloc] initWithNibName:@"PersonListViewController" bundle:[NSBundle mainBundle]];
	navControllerRecents = [[UINavigationController alloc] initWithNibName:@"RecentListViewController" bundle:[NSBundle mainBundle]];
	tabBarController = [[UITabBarController alloc] init];
	
	PersonListViewController *personListViewController = [[PersonListViewController alloc] initWithStyle:UITableViewStylePlain];
	RecentListViewController *recentListViewController = [[RecentListViewController alloc] init];
		
	tabBarController.viewControllers = [NSArray arrayWithObjects: navControllerContacts, navControllerRecents, nil];	
	
	[navControllerContacts pushViewController:personListViewController animated:NO];
	[navControllerRecents pushViewController:recentListViewController animated:NO];
	
	[PersonListViewController release];
	[RecentListViewController release];

	[window addSubview:tabBarController.view];
	[window makeKeyAndVisible];
		
	return YES;
}


- (void)fillDB {
	
	NSLog(@"No Database created yet: Load plist!");
	flickrContext = [flickrFetcher managedObjectContext];
	
	// Documents directory 
	NSString *documentsPath = [self applicationDocumentsDirectory];
	NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"FakeData.plist"];

	
	//Pull the data from the Bundle object in the Resources directory...
	NSFileManager *defaultFile = [NSFileManager defaultManager];
	BOOL isInstalled = [defaultFile fileExistsAtPath :plistPath];
	
	NSArray *plistData = [NSArray arrayWithContentsOfFile:plistPath];

	if(isInstalled == NO)
	{      
		NSLog(@"Initial installation: retrieve and copy FakeData.plist from Main Bundle");

		NSString *bundlePath = [[NSBundle mainBundle] pathForResource :@"FakeData" ofType:@"plist"];
		plistData = [NSArray arrayWithContentsOfFile:bundlePath];

		if(plistData)
		{
			[plistData writeToFile:plistPath atomically:YES];
			//OR... [defaultFile copyItemAtPath:bundlePath toPath:plistPath error:&errorDesc];
		}      
	}

	//Process plistData to store in Photo and Person objects...
	NSEnumerator *enumr = [plistData objectEnumerator];
	id curr = [enumr nextObject];
	NSMutableArray *names = [[NSMutableArray alloc] init];

	
	// Cuidado con los nombres que no he sido demasiado claro y name lo uso en ambos cuando
	// debería haber explicado mejor todo!
	
	while (curr != nil) {
		Photo *photo = (Photo *) [NSEntityDescription insertNewObjectForEntityForName:@"Photo" 
													 inManagedObjectContext:flickrContext];
		[photo setName:[curr objectForKey:@"name"]];
		[photo setPath:[curr objectForKey:@"path"]];
		
		//See if the name has already been set for a Person object...
		NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ IN %@", [curr objectForKey:@"user"], names];
		BOOL doesExist = [predicate evaluateWithObject :curr];
		
		if (doesExist == NO)
		{
			Person *person = [NSEntityDescription insertNewObjectForEntityForName :@"Person" inManagedObjectContext:flickrContext];
			
			[person setName:[curr objectForKey:@"user"]];
			[person addPhotosObject:photo];
			[photo setOwner:person];
			NSLog(@"Person OBJECT: %@", person);
			[names addObject :[curr objectForKey :@"user"]];
		}
		else {
			NSArray *objectArray = [flickrFetcher fetchManagedObjectsForEntity :@"Person" withPredicate:predicate];
			Person *person = [objectArray objectAtIndex:0];
			[photo setOwner:person];
			[objectArray release];
			
		}
		curr = [enumr nextObject];
	}
	[names release];
	
}


/**
 * Saves changes in the application's managed object context before the application terminates.
 */
-(void)applicationDidEnterBackground:(UIApplication *)application
{

}//END


#pragma mark -
#pragma mark Application's Documents directory
/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


- (void)dealloc {
	
	
	[flickrFetcher release];
	[flickrContext release];
	
	[tabBarController release];
	[navControllerContacts release];
	[navControllerRecents release];
	[window release];
	[super dealloc];
}


@end
